package com.sgcc.pda.bluetooth.bluetoothmanager;

import android.app.AlertDialog;
import android.app.Application;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.clj.fastble.data.BleDevice;
import com.sgcc.pda.bluetooth.api.BlueDeviceEntity;
import com.sgcc.pda.bluetooth.api.IBlueConnStatusListener;
import com.sgcc.pda.bluetooth.api.IReceiveCallBack;
import com.sgcc.pda.bluetooth.blueinterface.ConnectBlueCallBack;
import com.sgcc.pda.bluetooth.blueinterface.IBleConnectListener;
import com.sgcc.pda.bluetooth.blueinterface.IOnReConnectListener;
import com.sgcc.pda.bluetooth.config.Constant;
import com.sgcc.pda.bluetooth.ui.BluetoothListActivity;
import com.sgcc.pda.bluetooth.utils.BlueDeviceInfoUtil;
import com.sgcc.pda.bluetooth.utils.ToolGson;
import com.sgcc.pda.mdrh.task.lib_tools_bluetool.R;

import static com.sgcc.pda.bluetooth.config.Constant.BLUE_BLE;
import static com.sgcc.pda.bluetooth.config.Constant.BLUE_CLS;
import static com.sgcc.pda.bluetooth.config.Constant.CONNECTED;

/**
 * 描 述：蓝牙管理类 经典、ble
 * 作 者：yangzhi
 * 时 间：2020/3/5 10:49
 * 版 本：1.0
 * 版 权： Copyright (c) remarkables-united.Co.Ltd. All rights reserved.
 */
public class BlueManager {

    private static final String TAG = "BlueManager";
    private static final int CONN_START = 1;
    private static final int CONN_SUCC = 2;
    private static final int CONN_FAIL = 3;
    private Context mContext;
    private static BlueManager mInstance;
    //private int blueType = BLUE_BLE;//蓝牙类型
    //蓝牙类型,默认经典蓝牙
    private int blueType = BLUE_CLS;
    //是否自动连接,默认自动连接
    private boolean isAutoReConn = true;
    //自动重连次数  默认3次
    private int mReConnCount = 3;

    public static BlueManager getInstance(Context context) {
        synchronized (BlueManager.class) {
            if (null == mInstance) {
                mInstance = new BlueManager(context);
            }
        }
        return mInstance;
    }

    private BlueManager(Context context) {
        this.mContext = context;
    }


    /**
     * 获取蓝牙类型
     *
     * @return 经典/ble
     */
    public int getBlueType() {
        return blueType;
    }


    /**
     * 设置蓝牙类型
     *
     * @param blueType   经典/ble
     * @param autoReConn 是否自动连接
     */
    public void setBlueType(int blueType, boolean autoReConn, int reConnCount) {
        this.blueType = blueType;
        isAutoReConn = autoReConn;
        this.mReConnCount = reConnCount;
    }

    /**
     * 获取自动连接
     *
     * @return true/false
     */
    public boolean isAutoReConn() {
        return isAutoReConn;
    }

    /**
     * 获取自动重连次数
     *
     * @return
     */
    public int getmReConnCount() {
        return mReConnCount;
    }

    /**
     * 配置蓝牙
     *
     * @param type         蓝牙类型
     * @param isAutoReConn 自动连接
     * @param reConnCount  最大重连次数
     */
    public void configBlue(Application application, int type, boolean isAutoReConn, int reConnCount) {
        if (BLUE_BLE == type) {
            //ble蓝牙
            BleBluetoothManager.getInstance(mContext).configBlue(application, isAutoReConn, reConnCount);
        } else if (BLUE_CLS == type) {
            //经典蓝牙
            ClassicBluetoothManager.getInstance(mContext).configBlue(isAutoReConn, reConnCount);
        }

    }


    /**
     * 返回蓝牙对象 名称、地址、连接状态
     */
    public BlueDeviceEntity getBlueDeviceEntity() {
        return BlueDeviceInfoUtil.getInstance().getDeviceInfo();
    }

    /**
     * 返回蓝牙对象 名称、地址、连接状态
     */
    public BluetoothDevice getClsBlueDevice() {
        return BlueDeviceInfoUtil.getInstance().getClsDevice();
    }

    /**
     * 发送数据
     *
     * @param data     发送都数据
     * @param callBack 发送数据回调 只有接收结果返回
     */
    public void sendData(final String data, final IReceiveCallBack callBack) {
        if (BLUE_BLE == blueType) {
            //ble蓝牙
            //获取最近连接的蓝牙对象
            final BleDevice bleDevice = BlueDeviceInfoUtil.getInstance().getBleDevice();
            if (null != bleDevice) {
                if (BleBluetoothManager.getInstance(mContext).isConn(bleDevice)) {
                    //已连接，收发数据
                    BleBluetoothManager.getInstance(mContext).sendData(bleDevice, data, callBack);
                } else {
                    //自动连接
                    BleBluetoothManager.getInstance(mContext).startConn(bleDevice, new IBleConnectListener() {
                        @Override
                        public void onStartConn() {
                            showProgressDialog("蓝牙自动连接中...");
                        }

                        @Override
                        public void onConnSuccess() {
                            hideProgressDialog();
                            Toast.makeText(mContext, "自动连接成功", Toast.LENGTH_SHORT).show();
                            if (null != bleDevice) {
                                BlueDeviceInfoUtil.getInstance().setDeviceInfo(BLUE_BLE, ToolGson.getJsonStr(bleDevice), CONNECTED);
                            }
                            //已连接，收发数据
                            BleBluetoothManager.getInstance(mContext).sendData(bleDevice, data, callBack);
                        }

                        @Override
                        public void onConnFailure(String error) {
                            hideProgressDialog();
                            BlueDeviceInfoUtil.getInstance().setDeviceInfo(BLUE_BLE, ToolGson.getJsonStr(bleDevice), Constant.DISCONNECTED);
                            Toast.makeText(mContext, "自动连接失败", Toast.LENGTH_SHORT).show();
                            //打开界面去连接
                            showBluetoothView();
                        }
                    });
                }

            } else {
                //打开界面去连接
                showBluetoothView();
            }

        } else if (BLUE_CLS == blueType) {
            //经典蓝牙
            //获取最近连接的蓝牙对象
            final BluetoothDevice bluetoothDevice = BlueDeviceInfoUtil.getInstance().getClsDevice();
            if (null != bluetoothDevice) {
                if (ClassicBluetoothManager.getInstance(mContext).isConnectBlue(bluetoothDevice)) {
                    //已连接，收发数据
                    ClassicBluetoothManager.getInstance(mContext).sendData(data, callBack);
                } else {
                    //自动连接
                    ClassicBluetoothManager.getInstance(mContext).connect(bluetoothDevice, new ConnectBlueCallBack() {
                        @Override
                        public void onStartConnect() {
                            if (null != mHandler) {
                                mHandler.sendEmptyMessage(CONN_START);
                            }
                        }

                        @Override
                        public void onConnectSuccess(BluetoothDevice bluetoothDevice) {
                            if (null != mHandler) {
                                mHandler.sendEmptyMessage(CONN_SUCC);
                            }
                            if (null != bluetoothDevice) {
                                Log.e(TAG, "连接成功，保存对象" + bluetoothDevice.getAddress());
                                BlueDeviceInfoUtil.getInstance().setDeviceInfo(BLUE_CLS, ToolGson.getJsonStr(bluetoothDevice), Constant.CONNECTED);
                            }

                            //已连接，收发数据
                            ClassicBluetoothManager.getInstance(mContext).sendData(data, callBack);
                        }

                        @Override
                        public void onConnectFail() {
                            BlueDeviceInfoUtil.getInstance().setDeviceInfo(BLUE_CLS, ToolGson.getJsonStr(bluetoothDevice), Constant.DISCONNECTED);
                            if (null != mHandler) {
                                mHandler.sendEmptyMessage(CONN_FAIL);
                            }
                        }
                    });

                }

            } else {
                //打开界面去连接
                showBluetoothView();
            }
        }

    }

    /**
     * 取消扫描
     */
    public void cancelScan() {
        if (BLUE_BLE == blueType) {
            //ble蓝牙
            BleBluetoothManager.getInstance(mContext).cancelScan();
        } else if (BLUE_CLS == blueType) {
            //经典蓝牙
            ClassicBluetoothManager.getInstance(mContext).cancelScan();
        }
    }

    /**
     * 断开已有的连接
     */
    public void clearConnectedThread() {
        //获取最近连接的蓝牙对象
        if (BLUE_BLE == blueType) {
            //ble蓝牙
            BleDevice bleDevice = BlueDeviceInfoUtil.getInstance().getBleDevice();
            if (null != bleDevice) {
                BleBluetoothManager.getInstance(mContext).dissConnect(bleDevice);
            }
        } else if (BLUE_CLS == blueType) {
            //经典蓝牙
            ClassicBluetoothManager.getInstance(mContext).setActiveDisConnected(true);
            BluetoothDevice bluetoothDevice = BlueDeviceInfoUtil.getInstance().getClsDevice();
            if (null != bluetoothDevice) {
                ClassicBluetoothManager.getInstance(mContext).cancelConnect();
            }
        }
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CONN_START: //开始自动连接
                    try {
                        showProgressDialog("蓝牙自动连接中...");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case CONN_SUCC://自动连接成功
                    try {
                        Toast.makeText(mContext, "自动连接成功", Toast.LENGTH_SHORT).show();
                        hideProgressDialog();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case CONN_FAIL://自动连接失败
                    try {
                        Toast.makeText(mContext, "自动连接失败", Toast.LENGTH_SHORT).show();
                        hideProgressDialog();
                        //打开界面去连接
                        showBluetoothView();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 已连接蓝牙状态监听
     * 已连接、已断开
     *
     * @param blueConnStatusListener 连接状态监听
     */
    public void setOnBlueConnStatusListener(IBlueConnStatusListener blueConnStatusListener) {
        BluetoothListActivity.setBlueConnStatusListener(blueConnStatusListener);
    }

    /**
     * 设置自动重连的监听
     *
     * @param onReConnectListener 自动重连监听
     */
    public void setAutoConnListener(IOnReConnectListener onReConnectListener) {
        if (BLUE_CLS == blueType) {
            //经典蓝牙
            ClassicBluetoothManager.getInstance(mContext).setAutoConnListener(onReConnectListener);
        } else if (BLUE_BLE == blueType) {
            BleBluetoothManager.getInstance(mContext).setAutoConnListener(onReConnectListener);
        }
    }

    /**
     * 打开蓝牙界面
     */
    public void showBluetoothView() {
        Intent intent = new Intent();
        intent.setClass(mContext, BluetoothListActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    /**
     * 判断蓝牙是否可用
     */
    public boolean isBlueEnable() {
        if (BLUE_BLE == blueType) {
            //ble蓝牙
            return BleBluetoothManager.getInstance(mContext).isBlueEnable();
        } else if (BLUE_CLS == blueType) {
            //经典蓝牙
            return ClassicBluetoothManager.isBlueEnable();
        }
        return false;
    }

    private AlertDialog alertDialog;

    /**
     * 展示提示框
     *
     * @param mes 提示框文字信息
     */
    private void showProgressDialog(String mes) {
        if (alertDialog == null) {
            @SuppressWarnings("AliDeprecation") ProgressDialog.Builder builder = new ProgressDialog.Builder(mContext);
            builder.setCancelable(true);
            alertDialog = builder.create();
        }
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.dialog_loading);
        TextView textView = window.findViewById(R.id.tv_dialog_msg);
        textView.setText(mes);
    }

    /**
     * 隐藏提示框
     */
    private void hideProgressDialog() {
        if (alertDialog != null) {
            alertDialog.dismiss();
        }
    }

    /**
     * 销毁handler
     */
    public void removeHandler() {
        if (null != mHandler) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

}


